package com.ruoyi.quartz.task;

import cn.hutool.extra.qrcode.BufferedImageLuminanceSource;
import cn.hutool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.*;
import com.google.zxing.common.HybridBinarizer;
import com.ruoyi.business.domain.*;
import com.ruoyi.business.param.MsgPayResult;
import com.ruoyi.business.response.ResponseData;
import com.ruoyi.business.service.*;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.payment.pbqzpay.PubuPayUtils;
import com.ruoyi.common.utils.redis.RedisUtil;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 定时任务调度测试
 *
 * @author admin
 */
@Component("pbqzOrderCheckTask")
public class PbqzOrderCheckTask {
    @Resource
    private ITOrderInfoService orderService;
    @Resource
    private ITRecipientInfoService userRecipientService;
    @Resource
    private ChargeService chargeService;
    @Resource
    private LoginService loginService;
    private Log logger = Log.get();

    @Autowired
    private ITSmjGoodListService itSmjGoodListService;

    @Autowired
    private ITSmjMachineListService itSmjMachineListService;

    @Autowired
    private ITSmjOrderInfoService itSmjOrderInfoService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 检查支付超时的订单。状态为待支付并且当前时间已经超过有效时间
     */
    public void checkOrder() throws Exception {
//        logger.info("CXZF订单查询..");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        TOrderInfo query = new TOrderInfo();
//        query.setChannelType("alipay");
        query.setChannel("pbqz_");
        query.setStatus(1);
        String newdateTime = DateUtils.dealDate("10分钟前");
//        String dateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        query.getParams().put("beginCreateTime", newdateTime);
        List<TOrderInfo> orderInfos = orderService.selectTOrderInfoListByNoAuth(query);
        for (TOrderInfo orderInfo : orderInfos) {
            synchronized (this) {
                if (orderInfo.getValidTime().before(new Date()) || StringUtils.isBlank(orderInfo.getPay3rdOrderNo())) {
                    continue;
                }

                TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
                String accountJson = userRecipientInfo.getAccountJson();
                JSONObject accountObj = JSONObject.parseObject(accountJson);
                String token = accountObj.getString("token");
                HashMap<String, String> headerMap = new HashMap();
                headerMap.put("Cookie", accountObj.getString("cookie"));
                headerMap.put("User-Agent", accountObj.getString("User-Agent"));
                LocalDate now = LocalDate.now();
                JSONObject reqOrderObj = new JSONObject();
                reqOrderObj.put("endDate", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                reqOrderObj.put("scopeFlag", "1");
                reqOrderObj.put("queryDate", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                logger.info("查单参数：{}", JSON.toJSONString(reqOrderObj));
                long time = System.currentTimeMillis()/1000;
                String sign = PubuPayUtils.getSign(time,reqOrderObj,token);
                String submitPayUrl = "http://api.openpubu.com/order/orderListNew?token="+token+"&time="+time+"&sign="+sign+"&client_channel=2&api_version=2.2.5";
                String submitPayRes = HttpUtils.sendJsonMessage(submitPayUrl,headerMap,reqOrderObj.toJSONString());
//                logger.info("查单返回：{}", submitPayRes);
                JSONObject  submitPayResObj = JSONObject.parseObject(submitPayRes);
                if(submitPayResObj.getIntValue("status")!=200){
                    if(submitPayResObj.getIntValue("status")==499){
                        userRecipientInfo = reLogin(userRecipientInfo);
                        submitPayResObj = rePaydetail(userRecipientInfo,submitPayResObj);
                    }
                }
                logger.info(submitPayResObj.toJSONString());
                JSONArray resultList = submitPayResObj.getJSONObject("body").getJSONArray("recordList");
                for (int i = 0; i < resultList.size(); i++) {
                    JSONObject result = (JSONObject) resultList.get(i);
                    Date payTime = sdf.parse(result.getString("tradeTime"));

                    boolean flag = false;
                    logger.info("支付时间是否大于更新时间：{},支付时间是否小于失效时间:{}", payTime.after(orderInfo.getUpdateTime()), payTime.before(orderInfo.getValidTime()));

                    if (payTime.after(orderInfo.getUpdateTime()) && payTime.before(orderInfo.getValidTime())) {
                        logger.info("订单修改时间：{},订单支付时间:{},订单失效时间：{}", sdf.format(orderInfo.getUpdateTime()), sdf.format(payTime), sdf.format(orderInfo.getValidTime()));
                        flag = true;
                    }
                    BigDecimal payAmount = new BigDecimal(orderInfo.getMoney() / 100).setScale(2);
                    //if (result.getString("outTradeNo").equals(orderInfo.getPay3rdOrderNo()) && result.getString("saleLocName").equals(orderInfo.getQrcodeContent()) && result.getString("rackNo").equals(tSmjGoodList.getGoodHd()) && new BigDecimal(result.getString("salePrice")).compareTo(payAmount) == 0 && flag) {
                    if (result.getString("status").equals("1") && result.getString("orderId").equals(orderInfo.getPay3rdOrderNo()) && new BigDecimal(result.getString("payMoneyText")).compareTo(payAmount) == 0) {
                        MsgPayResult msgPayResult = new MsgPayResult();
                        msgPayResult.setChannel(orderInfo.getChannel());
                        msgPayResult.setTradeNo(orderInfo.getId().toString());
                        msgPayResult.setChannelAccount(userRecipientInfo.getChannelAccount());
                        msgPayResult.setOrderId(orderInfo.getPay3rdOrderNo());
                        msgPayResult.setRealMoney(MoneyUtil.fenToYuan(orderInfo.getMoney() + ""));
                        msgPayResult.setUid(userRecipientInfo.getUserId().toString());
                        msgPayResult.setBillTime(sdf.format(payTime));

                        msgPayResult.setChannelPayMsgResult(result.toJSONString());
                        ResponseData responseData = chargeService.updateOrderPayResult(false, orderInfo.getId(), msgPayResult, false);
                        chargeService.notifyUserPaySucc(orderInfo.getId());

                        logger.info("瀑布圈子订单回调..订单号：" + orderInfo.getId() + " 金额：" + orderInfo.getMoney() + " 处理结果：{}", responseData.getSuccess());
                    }

                }
            }
        }
    }


    private TRecipientInfo reLogin(TRecipientInfo tRecipientInfo) {
        long time = System.currentTimeMillis()/1000;
        String accountJson = tRecipientInfo.getAccountJson();
        JSONObject  accountObj = JSONObject.parseObject(accountJson);
        HashMap<String, String> headerMap = new HashMap();
        JSONObject  loginObj  = new JSONObject();
        loginObj.put("pwd",accountObj.getString("password"));
        loginObj.put("userName",tRecipientInfo.getChannelAccount());
        String sign = PubuPayUtils.getSign(time,loginObj,"");
        String loginUrl = "http://api.openpubu.com/open/login?token=&time="+time+"&sign="+sign+"&client_channel=2&api_version=2.2.5";
        String loginRes = HttpUtils.sendJsonMessage(loginUrl,headerMap,loginObj.toJSONString());
        JSONObject  loginResObj = JSONObject.parseObject(loginRes);
        if(loginResObj.getIntValue("status")!=200){
            return tRecipientInfo;
        }
        JSONObject userObj = (JSONObject)loginResObj.getJSONObject("body").getJSONArray("userList").get(0);

        String token = userObj.getString("token");
        accountObj.put("token",token);
        tRecipientInfo.setAccountJson(accountObj.toJSONString());
        tRecipientInfo.setOnline(1);
        userRecipientService.updateTRecipientInfo(tRecipientInfo);
        return tRecipientInfo;
    }

    private JSONObject rePaydetail(TRecipientInfo tRecipientInfo,JSONObject  reqOrderObj) {
        long time = System.currentTimeMillis()/1000;
        String accountJson = tRecipientInfo.getAccountJson();
        JSONObject  accountObj = JSONObject.parseObject(accountJson);
        HashMap<String, String> headerMap = new HashMap();
        String token = accountObj.getString("token");
        String sign = PubuPayUtils.getSign(time,reqOrderObj,token);
        String submitPayUrl = "http://api.openpubu.com/order/orderListNew?token="+token+"&time="+time+"&sign="+sign+"&client_channel=2&api_version=2.2.5";
        String submitPayRes = HttpUtils.sendJsonMessage(submitPayUrl,headerMap,reqOrderObj.toJSONString());
        JSONObject  submitPayResObj = JSONObject.parseObject(submitPayRes);
        return submitPayResObj;
    }

}
